<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
    refreshSignupToken();
    require_once("signup_form.php");
    exit();
} else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (!isset($_POST['signup_token']) || $_POST['signup_token'] != $_SESSION['signup_token']) {
        fail("Invalid signup token!");
    }
    refreshSignupToken();

    require_once("db_connection.php");
    require_once("validator.php");
    $email = $_POST['email'];
    $password = $_POST['password'];
    $username = $_POST['username'];


    if (!validateUsername($username)) {
        fail("Invalid username pattern");
    }
    if (!validateEmail($email)) {
        fail("Invalid email pattern");
    }
    if (!validatePassword($password)) {
        fail("Invalid password pattern");
    }

    $conn = getdb();
    $stmt = $conn->prepare("INSERT INTO users(email, uname, pass_hash, salt, role) VALUES (:email,:uname,:pass_hash,:salt,:role)");

    $salt_key = time() . "+" . rand(0, 9999);
    $salt = md5($salt_key);
    $role = 1;//common user
    $pass_hash = hash_hmac("sha256", $password, $salt);

    try {
        $stmt->bindParam(':email', $email);
        $stmt->bindParam(':uname', $username);
        $stmt->bindParam(':pass_hash', $pass_hash);
        $stmt->bindParam(':salt', $salt);
        $stmt->bindParam(':role', $role);
        $stmt->execute();
    } catch (Exception $e) {
        fail("The email is registered!");
    }

    echo "<script>alert(\"Sign up successfully!\"); window.location.href=\"login.php\"</script>";
}

function fail($msg)
{
    echo "<script>alert(\"Sign up fail ! {$msg}\"); window.location.href=\"signup.php\"</script>";
    exit();
}

function refreshSignupToken()
{
    $signup_token = md5(time() . "signup_token" . rand(0, 9999));
    $_SESSION['signup_token'] = $signup_token;
}